/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Popup;
import javafx.stage.PopupWindow;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

/**
 *
 * @author enrico
 */
public class Biblioteca extends Application {

  /**
   * @param args the command line arguments
   */
  private BorderPane root;
  // Precaricamento
  //AggiungiLibroView alv = new AggiungiLibroView();
  private ListaLibriController llc = new ListaLibriController(this);
  private FindLibriController flc = new FindLibriController(this);
  private AnagraficaController ac = new AnagraficaController(this);
  private ModificaLibroController mlc = new ModificaLibroController(this);
  private PrestitiController pc = new PrestitiController(this);
  private MenuController menu = new MenuController(this);
  private Popup alert;
  private Scene scene;
  String messaggio;

  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage primaryStage) {
    /**
     * Aggiornamenti 
     */
    
    // 01/10/2012
    try {
      Class.forName("org.sqlite.JDBC");
      Connection conn = DriverManager.getConnection("jdbc:sqlite:lib/biblioteche.db");
      Statement stat = conn.createStatement();
      ResultSet rs = stat.executeQuery("PRAGMA table_info(prestiti)");

      boolean aggiornato = false;
      while (rs.next()) {
        if (rs.getString("name").equalsIgnoreCase("durata")) aggiornato = true;
      }
      
      if (!aggiornato) {
        stat.executeUpdate("ALTER TABLE prestiti ADD COLUMN durata NUMERIC");
      } else {
        // System.out.println("Tabella già aggiornata");
      }
      
      rs.close();
      stat.close();
      conn.close();
    } catch (Exception exc) {
      System.out.println("Impossibile controllare se il prestito ha già una durata.");
      exc.printStackTrace();
    }
    /*  FINE AGGIORNAMENTI  */
    
    primaryStage.setTitle("Biblioteca \"Antonio Carbonetti\"");

    // Aggiungo la divisione in due della finestra

    root = new BorderPane(); // GUI root
    root.setLeft(menu.getView());
    BorderPane bpTemp = new BorderPane();
    bpTemp.setCenter(new ImageView(new Image(getClass().getResourceAsStream("Stili/bibliologo.png"))));

    try {
      Class.forName("org.sqlite.JDBC");
      Connection conn = DriverManager.getConnection("jdbc:sqlite:lib/biblioteche.db");
      Statement stat = conn.createStatement();
      ResultSet rs = stat.executeQuery("select sum(quanti) as totale from biblioteche");
      String libriTotali = " libri memorizzati";
      while (rs.next()) {
        libriTotali = rs.getString("totale").replace(".0", "").concat(libriTotali);
      }
      bpTemp.setBottom(new Text(libriTotali));
      rs.close();
      stat.close();
      conn.close();
    } catch (Exception exc) {
      System.out.println("Biblioteca ->" + exc.getMessage());
    }

    bpTemp.setMinWidth(760);
    bpTemp.setMinHeight(500);
    root.setCenter(bpTemp);
    scene = new Scene(root, 1000, 650);
    scene.getStylesheets().add("Stili/stili.css");
    primaryStage.setScene(scene);
    primaryStage.show();
    primaryStage.centerOnScreen();
  }

  void changeMainPanel(String withWhat) {
    if (withWhat.equalsIgnoreCase("aggiungi")) {
      //root.setCenter(alv);
    } else if (withWhat.equalsIgnoreCase("cerca")) {
      root.setCenter(flc.getView());
    } else if (withWhat.equalsIgnoreCase("anagrafica")) {
      root.setCenter(ac.getView());
    } else if (withWhat.equalsIgnoreCase("prestiti")) {
      root.setCenter(pc.getView());
    }
    root.getCenter().setId("centerPane");
  }

  void changeMainPanel(String withWhat, int nBiblioteca) {

    if (withWhat.equalsIgnoreCase("lista")) {
      llc.setModelNumber(nBiblioteca);
      try {
        root.setCenter(llc.getView());

      } catch (ClassNotFoundException ex) {
        Logger.getLogger(Biblioteca.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SQLException ex) {
        Logger.getLogger(Biblioteca.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    root.getCenter().setId("centerPane");

  }

  public ModificaLibroController getModificaLibroController() {
    return mlc;
  }

  void showAlert(String testoAlert) {

    alert = new Popup();
    Label alertTesto = new Label(testoAlert);
    alertTesto.setId("testoAlert");
    alertTesto.setPrefSize(150, 80);
    alertTesto.setMaxSize(150, 80);
    alertTesto.setWrapText(true);

    Button si = new Button("Sì");
    si.setOnAction(new EventHandler<ActionEvent>() {

      @Override
      public void handle(ActionEvent e) {
        mlc.alertSurpassed(true);
        alert.hide();
      }
    });
    Button no = new Button("No");
    no.setOnAction(new EventHandler<ActionEvent>() {

      @Override
      public void handle(ActionEvent e) {
        mlc.alertSurpassed(false);
        alert.hide();
      }
    });

    GridPane grpn = new GridPane();

    Rectangle r = new Rectangle();
    r.setWidth(250);
    r.setHeight(150);
    r.setArcWidth(20);
    r.setArcHeight(20);
    r.setId("record-sales");

    Image alertI = new Image(getClass().getResourceAsStream("Stili/Alert.png"));
    ImageView alertIV = new ImageView(alertI);

    grpn.add(alertIV, 0, 0, 1, 2); // icona
    grpn.add(alertTesto, 1, 0, 2, 1);
    grpn.add(si, 1, 1);
    grpn.add(no, 2, 1);
    grpn.setHgap(20);
    grpn.setVgap(10);
    grpn.setMargin(alertIV, new Insets(15, 0, 0, 12));

    alert.getContent().addAll(r, grpn);
    alert.setAutoFix(true);
    alert.setOpacity(0.9);
    alert.setWidth(250);
    alert.setHeight(150);
    alert.setAutoHide(false);
    alert.setHideOnEscape(false);

    alert.setOnShowing(new EventHandler<WindowEvent>() {

      @Override
      public void handle(WindowEvent arg0) {
        // disabilita tutto
        root.setDisable(true);
      }
    });

    alert.setOnHidden(new EventHandler<WindowEvent>() {

      @Override
      public void handle(WindowEvent arg0) {
        root.setDisable(false);
      }
    });

    alert.show(getScene().getWindow());
    alert.centerOnScreen();

  }

  public BorderPane getRoot() {
    return root;
  }

  public Scene getScene() {
    return scene;
  }

  public ListaLibriController getListaController() {
    return llc;
  }

  void goToBook(LibroModel lm) {
    menu.visualizzaLibri("Sezione " + lm.getSezione());
    llc.goToBook(lm);
  }

  void setNuovoPrestito(int codiceLibro, int codicePersona, String data, int durata, int sezioneLibro) {
    pc.setNuovoPrestito(codiceLibro, codicePersona, data, durata);
    llc.setPrestato(codiceLibro,sezioneLibro);
  }
}
